<template>
  <a-table
    :data-source="tableData"
    :row-selection="{
      selectedRowKeys: selected,
      onChange: onSelectChange,
      getCheckboxProps: getCheckboxPropsHandler
    }"
    :columns="columns"
    :scroll="{ y: 240 }"
    row-key="orderWordId"
    :pagination="false"
    @change="onSelectChange"
  />
  <a-modal
    v-model:visible="visible"
    @ok="handleSubmit"
    width="800px"
    title="批量应用"
    :ok-text="okText"
    :confirm-loading="submitting"
    :after-close="handleClose"
  >
    <h3>应用列表</h3>
    <a-table :scroll="{ y: 240 }" :pagination="false" :data-source="batchTableData" :columns="batchColumns">
      <template #bodyCell="{ column, text }">
        <template v-if="column.key === 'upload'">
          <CheckCircleFilled class="success" v-if="text === BatchStatusEnum.Success"></CheckCircleFilled>
          <CloseCircleOutlined class="failed" v-else-if="text === BatchStatusEnum.Failed"></CloseCircleOutlined>
          <LoadingOutlined class="loading" v-else-if="text === BatchStatusEnum.Loading"></LoadingOutlined>
          <span v-else>等待</span>
        </template>
        <template v-if="column.key === 'message'">
          <a-tooltip>
            <template #title>{{ text || '--' }}</template>
            {{ text || '--' }}
          </a-tooltip>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useVModel } from '@vueuse/core'
import { message, type TableProps } from 'ant-design-vue'
import { calMode, type TargetKeyword } from '@/views/promotion/interface'
import { CheckCircleFilled, CloseCircleOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { compact, intersectionWith } from 'lodash-es'
import type { AxiosResponse } from 'axios'
import { useRouter } from 'vue-router'
import type { PromotionServiceApproveStatusEnum, PromotionServiceStatusEnum } from '@/core/enums/status'
import { PromotionServiceApproveStatusKeyMap, PromotionServiceStatusKeyMap } from '@/core/mapper/status'
import type { Creative } from '@/core/interfaces/promotion'
import { WordTypeEnum } from '@/core/enums/type'
import type { PlatformEnum } from '@/core/enums/platform'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { ProductEnum } from '@/core/enums/platform'
interface Props {
  selectedKeys: number[]
  tableData: Creative[]
  rawTableData: Creative[]
  showBatcher: boolean
  orderWordId?: number
  productId?: number
  clientType?: number
  batchSubmitter: (params: TargetKeyword) => Promise<[Error, AxiosResponse]>
  matchCampaignId: (clientType: PlatformEnum) => Creative['campaignId']
}

defineOptions({
  name: 'PromotionBatcher'
})

enum BatchStatusEnum {
  Pending,
  Loading,
  Success,
  Failed
}

const props = withDefaults(defineProps<Props>(), {
  selectedKeys: () => [],
  tableData: () => [],
  rawTableData: () => [],
  showBatcher: false
})

const router = useRouter()
const submitting = ref(false)
const visible = useVModel(props, 'showBatcher')
const selected = useVModel(props, 'selectedKeys')
const batchStatus = ref<Record<number, BatchStatusEnum>>({})
const batchMessage = ref<Record<number, string>>({})
// 这个批量应用需要带上当前关键词的id，因为当前关键词也得提交上去
const batchSelected = computed(() => {
  return sortSelected(compact([...selected.value, props.orderWordId]))
})
const batchTableData = computed(() => {
  return intersectionWith(props.rawTableData, batchSelected.value, (a, b) => a.orderWordId === b).map((item) => {
    return {
      ...item,
      upload: batchStatus.value[item.orderWordId] || BatchStatusEnum.Pending,
      message: batchMessage.value[item.orderWordId]
    }
  })
})
const batchSubmitted = ref(false)
const okText = computed(() => {
  return batchSubmitted.value ? '关闭' : '提交'
})

const defaultColumns = () => {
  return [
    {
      title: '关键词ID',
      dataIndex: 'orderWordId',
      key: 'orderWordId'
    },
    {
      title: '关键词',
      dataIndex: 'word',
      key: 'word',
      customRender: ({ text, record }: { text: string; record: Creative }) => {
        return record.type === WordTypeEnum.Zhzc
          ? `${text}（组）`
          : record.type === WordTypeEnum.Zxzc
            ? `${text}（赠）`
            : text
      }
    },
    {
      title: '端口',
      dataIndex: 'clientType',
      key: 'clientType',
      customRender: ({ text }: { text: PlatformEnum }) => PlatformKeyMap[text]
    },
    {
      title: '审核状态',
      dataIndex: 'serviceApproveStatus',
      key: 'serviceApproveStatus',
      customRender: ({ text }: { text: PromotionServiceApproveStatusEnum }) => {
        return PromotionServiceApproveStatusKeyMap[text]
      }
    },
    {
      title: '投放状态',
      dataIndex: 'serviceStatus',
      key: 'serviceStatus',
      customRender: ({ text }: { text: PromotionServiceStatusEnum }) => {
        return PromotionServiceStatusKeyMap[text]
      }
    }
  ]
}

const columns: TableProps['columns'] = defaultColumns()

const batchColumns = computed<TableProps['columns']>(() => {
  return [
    {
      title: '上传',
      dataIndex: 'upload',
      key: 'upload',
      width: '80px'
    },
    {
      title: '提示',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true
    },
    ...defaultColumns()
  ]
})

// 勾选的数据要根据列表的索引排个序
function sortSelected(keys: number[]) {
  const d: number[] = []
  keys.forEach((k) => {
    const i = props.rawTableData.findIndex((item) => item.orderWordId === k)
    if (i > -1) {
      d[i] = k
    }
  })
  return compact(d)
}

function onSelectChange(keys: number[]) {
  selected.value = sortSelected(keys)
}
const getCheckboxPropsHandler = (record: any) => {
  return {
    disabled:
      (props.productId === ProductEnum.BWSD || props.productId === ProductEnum.BWSDYXB) &&
      record.clientType !== props.clientType
  }
}

async function handleSubmit() {
  if (batchSubmitted.value) {
    visible.value = false
    return false
  }

  let errCount = 0

  submitting.value = true
  batchSubmitted.value = true
  for (let i = 0; i < batchTableData.value.length; i++) {
    const current = batchTableData.value[i]
    // 成功的就不再提交了
    if (batchStatus.value[current.orderWordId] === BatchStatusEnum.Success) {
      return
    }

    batchStatus.value[current.orderWordId] = BatchStatusEnum.Loading

    const [err] = await props.batchSubmitter({
      id: current.id,
      word: current.word,
      orderWordId: current.orderWordId,
      mode: calMode(current.id),
      groupId: current.groupId,
      creativeId: current.creativeId,
      clientType: current.clientType,
      pcGoods: current.pcGoods,
      wapGoods: current.wapGoods,
      campaignId: props.matchCampaignId(current.clientType)
    })

    if (!err) {
      batchStatus.value[current.orderWordId] = BatchStatusEnum.Success
      batchMessage.value[current.orderWordId] = '提交成功'
    } else {
      batchStatus.value[current.orderWordId] = BatchStatusEnum.Failed
      batchMessage.value[current.orderWordId] = err.message
      errCount += 1
    }
  }
  submitting.value = false

  if (errCount === 0) {
    batchSubmitted.value = false
    message.success('提交成功')
    visible.value = false
    setTimeout(() => {
      handleBack()
    }, 1000)
  }
}

function handleClose() {
  batchStatus.value = {}
  batchMessage.value = {}
  batchSubmitted.value = false
}

function handleBack() {
  router.go(-1)
}
</script>

<style lang="scss" scoped>
.success {
  color: #52c41a;
}

.failed {
  color: #ff4d4f;
}

.loading {
  color: #508fe8;
}
</style>
